<?php

namespace Gds\VenteBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Gds\VenteBundle\Entity\FactureAvoirClient;
use Gds\VenteBundle\Form\FactureAvoirClientType;
use Symfony\Component\HttpFoundation\Response;
use Gds\VenteBundle\Entity\LigneFactureAvoirClient;

class FactureAvoirController extends Controller {

    public function indexAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $societe = $em->getRepository('GdsArticleBundle:Societe')->findAll()[0];
        $ref = $societe->getPrefixeFactureAvoir();
        $ref_num = $societe->getNumeroFactureAvoir();
        $facture_avoir = new FactureAvoirClient();
        $facture_avoir->setReference($ref . ' ' . $ref_num);
        $form = $this->createForm(new FactureAvoirClientType, $facture_avoir);
        $user = $this->getUser();
        return $this->render('GdsVenteBundle:FactureAvoir:facture_avoir.html.twig', array('form' => $form->createView(), 'user' => $user));
    }

    public function getFacturesAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $date = $request->get('date');
        $id_client = $request->get('client');
        $client = $em->getRepository('GdsVenteBundle:Client')->find($id_client);
        $factures = $em->getRepository('GdsVenteBundle:FactureClient')->getWhereDateClient($date, $client);
        $result = array();
        foreach ($factures as $facture) {
            $fc = array();
            $fc['reference'] = $facture->getReference();
            $fc['id'] = $facture->getId();
            $result[] = $fc;
        }
        $response = new Response(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function factureAvoirAction() {
//        $em = $this->getDoctrine()->getEntityManager();
//        $request = $this->getRequest();
//        $id = $request->get('id');
//        $facture = $em->getRepository('GdsVenteBundle:FactureClient')->find($id);
//        $bons_livraison = $em->getRepository('GdsVenteBundle:BonLivraisonClient')->findByFacture($facture);
//        $client = $bons_livraison[0]->getClient();
//        $societe = $em->getRepository('GdsArticleBundle:Societe')->findAll()[0];
//        $ref = $societe->getPrefixeFactureAvoir();
//        $ref_num = $societe->getNumeroFactureAvoir();
//        $facture_avoir = new FactureAvoirClient();
//        $facture_avoir->setReference($ref . ' ' . $ref_num);
//        $form = $this->createForm(new FactureAvoirClientType, $facture_avoir);
//        if ($request->isMethod('POST')) {
//            $articles = json_decode($request->get('articles'));
//            $quantite_retour = 0;
//            foreach ($articles as $article)
//                $quantite_retour += $article->quantite;
//            if ($quantite_retour == 0) {
//                $response = new Response(json_encode(array('success' => false)));
//                $response->headers->set('Content-Type', 'application/json');
//                return $response;
//            }
//            $articles_facture = array();
//            foreach ($bons_livraison as $bon) {
//                $lignes = $em->getRepository('GdsVenteBundle:LigneBonLivraisonClient')->findBy(array('bon_livraison' => $bon));
//                foreach ($lignes as $ligne) {
//                    $article = $ligne->getArticle();
//                    if (!$this->isArticleExist($article, $articles)) {
//                        $articles[] = $article;
//                        $line = array();
//                        $taux_tva = $article->getTauxTva();
//                        $line['reference'] = $article->getReference();
//                        $line['designation'] = $article->getDesignation();
//                        $line['code_barre'] = $article->getCodeBarre();
//                        $line['taux_tva'] = $taux_tva;
//                        $line['quantite'] = $ligne->getQuantiteBlanc();
//                        $line['prix_vente'] = $ligne->getPrixUnitaireHt();
//                        $line['remise'] = $ligne->getTauxRemise();
//                        $name = $article->getReference() . ' : ' . $article->getDesignation();
//                        $line['name'] = $name;
//                        $line['id'] = $article->getId();
//                        $articles_facture[] = $line;
//                    } else {
//                        $k = $this->getIndexLines($article, $articles_facture);
//                        $articles_facture[$k]['quantite'] += $ligne->getQuantiteBlanc();
//                        $articles_facture[$k]['prix_vente'] = min($articles_facture[$k]['prix_vente'], $ligne->getPrixUnitaireHt());
//                        $articles_facture[$k]['remise'] = max($articles_facture[$k]['remise'], $ligne->getTauxRemise());
//                    }
//                }
//            }
//            $factures_avoir = $facture->getFacturesAvoirs();
            
//        }
        return $this->render('GdsVenteBundle:FactureAvoir:form_facture_avoir.html.twig', array('form' => $form->createView(), 'client' => $client, 'id' => $id));
    }

    public function getArticlesFromFactureAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $id = $request->get('id');
        $lines = array();
        $articles = array();
        $facture = $em->getRepository('GdsVenteBundle:FactureClient')->find($id);
        $bons_livraison = $em->getRepository('GdsVenteBundle:BonLivraisonClient')->findByFacture($facture);
        foreach ($bons_livraison as $bon_livraison) {
            $reference = $bon_livraison->getReference();
            $histories = $em->getRepository('GdsVenteBundle:HistoryBonLivraisonClient')->findByReference($reference);
            $is_facturer = false;
            $i = 0;
            while ($i < count($histories) && !$is_facturer) {
                if ($histories[$i]->getIsFacturer())
                    $is_facturer = true;
                else
                    $i++;
            }
            $history = $histories[$i - 1];
            $lignes = $em->getRepository('GdsVenteBundle:HistoryLigneBonLivraisonClient')->findBy(array('history_bon_livraison' => $history));
            foreach ($lignes as $ligne) {
                $article = $ligne->getArticle();
                if (!$this->isArticleExist($article, $articles)) {
                    $articles[] = $article;
                    $line = array();
                    $taux_tva = $article->getTauxTva();
                    $line['reference'] = $article->getReference();
                    $line['designation'] = $article->getDesignation();
                    $line['code_barre'] = $article->getCodeBarre();
                    $line['taux_tva'] = $taux_tva;
                    $line['quantite1'] = $ligne->getQuantiteBlanc();
                    $line['quantite2'] = $ligne->getQuantiteNoir();
                    $line['quantite_retour'] = $ligne->getQuantiteRetour();
                    $line['quantite'] = 0;
                    $line['prix_vente'] = $ligne->getPrixUnitaireHt();
                    $line['remise'] = $ligne->getTauxRemise();
                    $name = $article->getReference() . ' : ' . $article->getDesignation();
                    $line['name'] = $name;
                    $line['id'] = $article->getId();
                    $lines[] = $line;
                } else {
                    $k = $this->getIndexLines($article, $lines);
                    $lines[$k]['quantite1'] += $ligne->getQuantiteBlanc();
                    $lines[$k]['quantite2'] += $ligne->getQuantiteNoir();
                    $lines[$k]['quantite_retour'] += $ligne->getQuantiteRetour();
                    $lines[$k]['prix_vente'] = min($lines[$k]['prix_vente'], $ligne->getPrixUnitaireHt());
                    $lines[$k]['remise'] = max($lines[$k]['remise'], $ligne->getTauxRemise());
                }
            }
        }
        $response = new Response(json_encode($lines));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    function isArticleExist($art, $articles) {
        foreach ($articles as $article) {
            if ($article->getId() == $art->getId())
                return true;
        }
        return false;
    }

    function getIndexLines($article, $lines) {
        foreach ($lines as $k => $line) {
            if ($line['id'] == $article->getId())
                return $k;
        }
        return null;
    }

}
